package com.swq.java.code.chapter19.code22;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ColorChanger2 extends JPanel {
    private Color color = Color.RED;
    private int times; //跟踪调用paintComponent()方法的次数

    public ColorChanger2() {
        JButton button = new JButton("change color");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                color = (color == Color.RED) ? Color.GREEN : Color.RED;  //更换画笔的颜色
                repaint();  //刷新组件
                //打印执行该方法的线程
                System.out.println(Thread.currentThread().getName() + ":actionPerformed()");
            }
        });

        add(button);
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(color);  //设置画笔的颜色
        g.fillRect(0, 0, 300, 300);  //画一个矩形
        //跟踪该方法被调用的次数
        System.out.println("call paintComponent " + (++times) + " times");

        //打印执行该方法的线程
        System.out.println(Thread.currentThread().getName() + ":paintComponent()");
    }

    public static void createAndShowGUI() {
        JFrame frame = new JFrame("Hello");
        frame.setContentPane(new ColorChanger2());

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 300);
        frame.setVisible(true);

        //打印执行该方法的线程
        System.out.println(Thread.currentThread().getName() + ":createAndShowGUI()");
    }

    public static void main(String args[]) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}